package controller;

import entity.PageEntity;
import entity.User;
import service.UserService;
import utils.CookieUtils;
import utils.FileUploadUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserService();

    /**
     * 用户登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String checkCode = req.getParameter("checkCode");
        String isRemember = req.getParameter("isRememberMe");


        String sessionCode = (String) session.getAttribute("sessionCode");

        if (!sessionCode.equals(checkCode)) {
            req.setAttribute("error", "验证码错误");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        User user = userService.fingByUsername(username);

        if (user == null) {
            req.setAttribute("error", "用户名不存在");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        if (!user.getPassword().equals(password)) {
            req.setAttribute("error", "密码错误");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        //更改用户登录时间
        userService.updateLoginTime(user.getId());

        if("1".equals(isRemember)) {
            //说明用户勾选了‘记住我’
            Cookie cookie = new Cookie("userId", user.getId()+"");

            //设置cookie携带路径
            cookie.setPath("/");

            //cookie过期时间
            cookie.setMaxAge(60*60*24*30);

            //写回客户端
            resp.addCookie(cookie);
        }

        session.setAttribute("loginUser", user);
        resp.sendRedirect("/html/home.jsp");
    }


    /**
     * 用户注册
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);

        user.setLoginTime(new Date());
        user.setRegisterTime(new Date());
        user.setIsSecret("0");
        user.setLook(0L);

        userService.register(user);

        resp.sendRedirect("/index.jsp");
    }

    /**
     * 用户注销
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {

        // 清除session
        request.getSession().removeAttribute("loginUser");

        Cookie loginCookie = CookieUtils.getCookie(request, "userId");

        if (loginCookie != null) {

            // 销毁cookie
            loginCookie.setPath("/");
            loginCookie.setMaxAge(0);
            response.addCookie(loginCookie);
        }

        response.sendRedirect("/index.jsp");
    }

    /**
     * 根据用户名查询用户是否存在
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void checkUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");


        User user = userService.fingByUsername(username);

        resp.setContentType("application/json;charset=utf-8");


        if (user != null) {

            resp.getWriter().write("1");
        } else {
            resp.getWriter().write("0");
        }
    }

    /**
     * 根据邮箱进行校对
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void checkEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String email = req.getParameter("email");

        User user = userService.fingByEmail(email);

        resp.setContentType("application/json;charset=utf-8");

        if (user != null) {
            resp.getWriter().write("1");
        } else {
            resp.getWriter().write("0");
        }
    }

    protected void getCode(HttpServletRequest req, HttpServletResponse resp,HttpSession session) throws ServletException, IOException {
        String code = req.getParameter("code");
        session.setAttribute("code", code);
    }
    protected void resetUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();

//        String code = session.getAttribute("code").toString();
        String code = "123456";
        String formCode = req.getParameter("form-password");
        String userPassword = req.getParameter("password");
        String email = req.getParameter("form-username");

        User user = userService.fingByEmail(email);

        if (user == null) {
            session.setAttribute("error","邮箱不存在");
            resp.sendRedirect("/forget.jsp");
            return;
        }


        if(code.equals(formCode)) {
            user.setPassword(userPassword);
            userService.updatePassword(user);
            session.setAttribute("error","重置密码成功");
            resp.sendRedirect("/forget.jsp");
            return;
        }else{
            session.setAttribute("error","验证码输入错误");
            resp.sendRedirect("/forget.jsp");
            return;

        }


    }

    /**
     * 查询用户列表
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<User> userList = userService.findAll();

        req.setAttribute("userList", userList);
        req.getRequestDispatcher("/html/user.jsp").forward(req, resp);

    }

    /**
     * 用户搜索
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String searchVal = getParam(req).get("searchVal");

        List<User> userList = userService.search(searchVal);

        req.setAttribute("userList", userList);
        req.setAttribute("searchVal", searchVal);

        req.getRequestDispatcher("/html/user.jsp").forward(req, resp);

    }

    /**
     * 用户搜索+分页
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> params = getParam(req);

        String searchVal = params.get("searchVal") == null ? "" : params.get("searchVal");
        //当前页码
        Integer currPage = Integer.parseInt(params.get("currPage"));

        //查询分页信息
        PageEntity<User> pageData = userService.findPage(searchVal, currPage);

        //查询当前登录的用户关注了那些人List<Long>
         User loginUser = (User) req.getSession().getAttribute("loginUser");
         List<Long> focusIdList = userService.findFocusIdList(loginUser.getId());

        req.setAttribute("pageData", pageData);
        req.setAttribute("searchVal", searchVal);
        req.setAttribute("focusIdList", focusIdList);
        req.getRequestDispatcher("/html/user.jsp").forward(req, resp);

    }


    /**
     * 根据部门id查询员工
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findByDeptId(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Long deptId = Long.parseLong(req.getParameter("deptId"));

        List<User> userList = userService.findByDeptId(deptId);

        writerObjToString(resp, userList);
    }


    protected void userDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



        String flag = req.getParameter("flag");

        if ("detail".equals(flag)) {

            long userId = Long.parseLong(req.getParameter("userId"));

            //查询别人的详情
            User user = userService.findById(userId);


            //粉丝数
            Integer fansCount = userService.findFansCount(userId);

            //被看数+1
            userService.updateLook(userId);


            req.setAttribute("user", user);
            req.setAttribute("fansCount", fansCount);
            req.getRequestDispatcher("/html/user_detail.jsp").forward(req, resp);


        }else {
            //查询自己的详情

            User loginUser = (User) req.getSession().getAttribute("loginUser");


            //查询关注数
            Integer focusCount = userService.findFocusCount(loginUser.getId());

            req.setAttribute("focusCount", focusCount);
            req.getRequestDispatcher("/html/user_look.jsp").forward(req, resp);

        }


    }

    /**
     * 更新用户信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf8");

        String userName = req.getParameter("realName");
        System.out.println(userName);
        req.setCharacterEncoding("utf-8");
        //获取前端的所以信息
        Map<String, String> params = getParam(req);
        HttpSession session = req.getSession();

        User loginUser = (User) session.getAttribute("loginUser");

        loginUser.setRealName(params.get("realName"));
        loginUser.setDeptId(Long.parseLong(params.get("deptId")));
        loginUser.setDeptName(params.get("deptName"));
        loginUser.setPhone(params.get("phone"));
        loginUser.setAge(Long.parseLong(params.get("age")));
        loginUser.setInfo(params.get("info"));
        loginUser.setGender(params.get("gender"));

        if(params.get("isSecret") == null || "".equals(params.get("isSecret"))) {
            loginUser.setIsSecret("1");
        }else {
            loginUser.setIsSecret("0");
        }


        //更新数据库
        userService.update(loginUser);
        //更新session
        session.setAttribute("loginUser", loginUser);

        resp.sendRedirect("/user/userDetail");
    }

    protected void fileUpload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //上传文件，返回文件名字
        String filename = FileUploadUtils.upload("/upload", req);

//        String url = "http://localhost:8080/upload/" + filename;
        String url =  filename;

        //更新session
        HttpSession session = req.getSession();
        User loginUser = (User) session.getAttribute("loginUser");
        loginUser.setPic(url);
        session.setAttribute("loginUser", loginUser);

        //更新数据库
        userService.updatePic(loginUser.getId(),url);

        //把新的图片地址写回前端
        resp.getWriter().write(url);



    }

    /**
     * 加关注/取消关注
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addFocus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //前端传递的参数
        Long focusId = Long.parseLong(req.getParameter("userId"));

        //当前登录的用户id
        Long userId =loginUser.getId();

        //查询是否有关注过对方
        Boolean flag = userService.isFocus(userId,focusId);

        if(flag) {
            //取消关注
            userService.delFocus(userId,focusId);
            writerObjToString(resp,"0");
        }else {
            //加关注
            userService.addFocus(userId,focusId);
            writerObjToString(resp,"1");
        }
    }

    /**
     * 我的关注列表+分页
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void findFocusPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //前端传递的页码
        Integer currPage = Integer.parseInt(req.getParameter("currPage"));

        //查询这个人的关注列表
        Long userId = loginUser.getId();

        //查询分页信息
        PageEntity<User> pageData = userService.findFocusPage(currPage,userId);

        req.setAttribute("pageData", pageData);
        req.getRequestDispatcher("/html/my_user.jsp").forward(req, resp);


    }

    /**
     * 处理微信二维码页面请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void wx_login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

          Properties props = new Properties();
        props.load(UserService.class.getClassLoader().getResourceAsStream("wx_config.properties"));

        String redirectUri = props.getProperty("wx.redirect_uri");
        String appId = props.getProperty("wx.AppID");
        String appSecret = props.getProperty("wx.AppSecret");


        String url ="https://open.weixin.qq.com/connect/qrconnect?response_type=code"+
                "&appid=" + appId +
                "&redirect_uri=" + URLEncoder.encode(redirectUri) +
                "&scope=snsapi_login";

        resp.sendRedirect(url);

    }
}
